package servlet;

import pojo.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet(urlPatterns = "/editUser")
public class UserEditServlet extends HttpServlet {
    // alt + insert

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 3行固定代码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 接收参数
        String str_id = req.getParameter("id");
        // 把字符串的id转换为整数类型
        int id = Integer.parseInt(str_id);

        String nickname = req.getParameter("nickname");
        String email = req.getParameter("email");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        // 把字符串类型的日期转换为Date类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = simpleDateFormat.parse(birthday);

            // 创建用户对象
            User user = new User();
            user.setId(id);
            user.setUsername(nickname);
            user.setEmail(email);
            user.setSex(sex);
            user.setBirthday(date);

            // 创建业务层对象
            UserService userService = new UserService();
            int count = userService.editUser(user);

            // 判断
            if (count > 0) {
                // 重定向
                resp.sendRedirect("/user");
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
